package com.ljw.community.service.impl;

import com.ljw.community.entity.Comment;
import com.ljw.community.entity.User;
import com.ljw.community.mapper.CommentMapper;
import com.ljw.community.mapper.CommonMapper;
import com.ljw.community.mapper.UserMapper;
import com.ljw.community.service.CommentService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CommonMapper commonMapper;

    @Override
    public List<Comment> loadComments(String topicId) {
        List<Comment> commentsList = commentMapper.loadCommentsByTopicId(topicId);
        for (int i = 0; i < commentsList.size(); i++) {
            Comment dbComment = commentsList.get(i);

            //存在replyId
            if (dbComment.getReplyId() != null && !dbComment.getReplyId().isEmpty()) {
                String replyLoginName = commonMapper.getLoginNameById(dbComment.getReplyId());
                //存在id却找不到这个用户 判定为已被删除用户
                dbComment.setReplyLoginName(replyLoginName == null ? "已注销用户" : replyLoginName);
                commentsList.set(i, dbComment);
            }
        }
        return commentsList;
    }

    @Override
    public int comment(String topicId, String loginName, String content) {

        //判空
        if (ObjectUtils.isEmpty(topicId) || ObjectUtils.isEmpty(loginName) || ObjectUtils.isEmpty(content)) {
            return 0;
        }

        //处理content 取出回复的人
        int startIndex = content.indexOf("@");  //用@开头
        int spaceIndex = content.indexOf(" ");   //用空格结尾
        String replyLoginName = null;

        //存在@ 同时 @在第一位 同时 存在空格 同时 两字符中间有其他字符 视为回复
        if (spaceIndex > 0 && startIndex == 0 && spaceIndex - startIndex > 1) {
            replyLoginName = content.substring(startIndex + 1, spaceIndex);
            content = content.substring(spaceIndex + 1);
        }

        //执行插入
        Comment comment = new Comment();
        if (replyLoginName != null) {
            //添加判断防止不存在该用户
            User replyUser =  userMapper.getFullByLoginName(replyLoginName);
            comment.setReplyId(replyUser == null ? "" : replyUser.getId());
        } else {
            comment.setReplyId("");
        }
        comment.setContent(content);
        comment.setCreateTime(new Date());
        comment.setId(UUID.randomUUID().toString().replace("-", ""));
        comment.setCreatorId(userMapper.getFullByLoginName(loginName).getId());
        comment.setTopicId(topicId);

        return commentMapper.insert(comment);
    }
}
